import { create } from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'
import {
    Task,
    TaskResult,
    TaskStatusInfo,
    TaskParams,
    TaskStatus,
    CreateTaskRequest,
    UpdateTaskRequest
} from '@/types/task'
import { getApiClient } from '@/lib/mockApi'
import { ApiClientError } from '@/lib/apiError'

// 任务执行上下文接口
interface TaskExecutionContext {
    taskId: string
    startTime: Date
    estimatedCompletion?: Date
    progress: number
    currentStep: string
    totalSteps: number
    logs: TaskLog[]
}

// 任务日志接口
interface TaskLog {
    id: string
    timestamp: Date
    level: 'info' | 'warning' | 'error' | 'debug'
    message: string
    details?: Record<string, unknown>
}

// 任务队列项接口
interface TaskQueueItem {
    task: Task
    priority: number
    queuedAt: Date
    estimatedStartTime?: Date
}

// 错误信息接口
interface TaskErrorInfo {
    taskId: string
    message: string
    code?: string
    details?: Record<string, unknown>
    timestamp: Date
    retryCount: number
}

// 任务统计接口
interface TaskStatistics {
    total: number
    completed: number
    failed: number
    running: number
    pending: number
    cancelled: number
    averageExecutionTime: number
    successRate: number
}

export interface TaskStore {
    // 任务状态
    tasks: Record<string, Task>
    currentTask: Task | null
    taskQueue: TaskQueueItem[]
    executionContexts: Record<string, TaskExecutionContext>

    // 结果和状态
    results: Record<string, TaskResult[]>
    taskStatuses: Record<string, TaskStatusInfo>

    // 错误处理
    errors: Record<string, TaskErrorInfo>

    // 全局状态
    isProcessing: boolean
    maxConcurrentTasks: number
    runningTasks: Set<string>

    // 统计信息
    statistics: TaskStatistics

    // 配置
    config: {
        autoRetry: boolean
        maxRetryAttempts: number
        retryDelay: number
        enableLogging: boolean
        pollingInterval: number
    }

    // Actions - 任务管理
    loadTasks: (datasetId: string) => Promise<void>
    createTask: (taskData: CreateTaskRequest) => Promise<Task>
    updateTask: (taskId: string, updates: UpdateTaskRequest) => Promise<Task>
    deleteTask: (taskId: string) => Promise<void>

    // Actions - 任务执行
    startTask: (taskId: string, params?: TaskParams) => Promise<void>
    cancelTask: (taskId: string) => Promise<void>
    retryTask: (taskId: string) => Promise<void>
    pauseTask: (taskId: string) => Promise<void>
    resumeTask: (taskId: string) => Promise<void>

    // Actions - 队列管理
    addToQueue: (task: Task, priority?: number) => void
    removeFromQueue: (taskId: string) => void
    reorderQueue: (taskIds: string[]) => void
    processQueue: () => Promise<void>
    clearQueue: () => void

    // Actions - 状态管理
    updateTaskStatus: (taskId: string, status: TaskStatusInfo) => void
    pollTaskStatus: (taskId: string) => Promise<void>
    startStatusPolling: (taskId: string) => void
    stopStatusPolling: (taskId: string) => void

    // Actions - 结果管理
    loadTaskResults: (taskId: string) => Promise<void>
    addTaskResult: (taskId: string, result: TaskResult) => void
    clearTaskResults: (taskId: string) => void

    // Actions - 错误处理
    handleTaskError: (taskId: string, error: unknown) => void
    clearTaskError: (taskId: string) => void
    clearAllErrors: () => void

    // Actions - 日志管理
    addTaskLog: (taskId: string, log: Omit<TaskLog, 'id' | 'timestamp'>) => void
    getTaskLogs: (taskId: string) => TaskLog[]
    clearTaskLogs: (taskId: string) => void

    // Actions - 统计和配置
    updateStatistics: () => void
    updateConfig: (config: Partial<TaskStore['config']>) => void
    resetStore: () => void
}

// 默认配置
const defaultConfig = {
    autoRetry: true,
    maxRetryAttempts: 3,
    retryDelay: 5000, // 5秒
    enableLogging: true,
    pollingInterval: 2000 // 2秒
}

// 默认统计
const defaultStatistics: TaskStatistics = {
    total: 0,
    completed: 0,
    failed: 0,
    running: 0,
    pending: 0,
    cancelled: 0,
    averageExecutionTime: 0,
    successRate: 0
}

// 生成唯一ID
const generateId = (): string => {
    return `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
}

// 创建错误信息
const createTaskError = (taskId: string, error: unknown, retryCount = 0): TaskErrorInfo => {
    if (error instanceof ApiClientError) {
        return {
            taskId,
            message: error.message,
            code: error.code,
            details: error.details,
            timestamp: new Date(),
            retryCount
        }
    }

    if (error instanceof Error) {
        return {
            taskId,
            message: error.message,
            timestamp: new Date(),
            retryCount
        }
    }

    return {
        taskId,
        message: '未知任务错误',
        timestamp: new Date(),
        retryCount
    }
}

// 状态轮询管理器
class StatusPollingManager {
    private intervals: Map<string, NodeJS.Timeout> = new Map()

    start(taskId: string, callback: () => Promise<void>, interval: number) {
        this.stop(taskId) // 清除现有的轮询

        const intervalId = setInterval(async () => {
            try {
                await callback()
            } catch (error) {
                console.error(`Status polling error for task ${taskId}:`, error)
                this.stop(taskId)
            }
        }, interval)

        this.intervals.set(taskId, intervalId)
    }

    stop(taskId: string) {
        const intervalId = this.intervals.get(taskId)
        if (intervalId) {
            clearInterval(intervalId)
            this.intervals.delete(taskId)
        }
    }

    stopAll() {
        this.intervals.forEach((intervalId) => clearInterval(intervalId))
        this.intervals.clear()
    }
}

const pollingManager = new StatusPollingManager()

export const useTaskStore = create<TaskStore>()(
    subscribeWithSelector((set, get) => ({
        // 初始状态
        tasks: {},
        currentTask: null,
        taskQueue: [],
        executionContexts: {},
        results: {},
        taskStatuses: {},
        errors: {},
        isProcessing: false,
        maxConcurrentTasks: 3,
        runningTasks: new Set(),
        statistics: { ...defaultStatistics },
        config: { ...defaultConfig },

        // Actions - 任务管理
        loadTasks: async (datasetId: string) => {
            try {
                const apiClient = await getApiClient()
                const tasks = await apiClient.getTasks(datasetId)
                const tasksMap = tasks.reduce((acc, task) => {
                    acc[task.id] = task
                    return acc
                }, {} as Record<string, Task>)

                set({ tasks: tasksMap })
                get().updateStatistics()
            } catch (error) {
                console.error('Failed to load tasks:', error)
                throw error
            }
        },

        createTask: async (taskData: CreateTaskRequest) => {
            try {
                const apiClient = await getApiClient()
                const task = await apiClient.createTask(taskData)
                set(state => ({
                    tasks: { ...state.tasks, [task.id]: task }
                }))
                get().updateStatistics()
                return task
            } catch (error) {
                console.error('Failed to create task:', error)
                throw error
            }
        },

        updateTask: async (taskId: string, updates: UpdateTaskRequest) => {
            try {
                const apiClient = await getApiClient()
                const updatedTask = await apiClient.updateTask(taskId, updates)
                set(state => ({
                    tasks: { ...state.tasks, [taskId]: updatedTask }
                }))
                return updatedTask
            } catch (error) {
                console.error('Failed to update task:', error)
                throw error
            }
        },

        deleteTask: async (taskId: string) => {
            try {
                const apiClient = await getApiClient()
                await apiClient.deleteTask(taskId)
                set(state => {
                    const { [taskId]: deleted, ...remainingTasks } = state.tasks
                    const { [taskId]: deletedResults, ...remainingResults } = state.results
                    const { [taskId]: deletedStatus, ...remainingStatuses } = state.taskStatuses
                    const { [taskId]: deletedError, ...remainingErrors } = state.errors

                    return {
                        tasks: remainingTasks,
                        results: remainingResults,
                        taskStatuses: remainingStatuses,
                        errors: remainingErrors,
                        taskQueue: state.taskQueue.filter(item => item.task.id !== taskId)
                    }
                })

                pollingManager.stop(taskId)
                get().updateStatistics()
            } catch (error) {
                console.error('Failed to delete task:', error)
                throw error
            }
        },

        // Actions - 任务执行
        startTask: async (taskId: string, params?: TaskParams) => {
            const store = get()
            const task = store.tasks[taskId]

            if (!task) {
                throw new Error(`Task ${taskId} not found`)
            }

            if (store.runningTasks.size >= store.maxConcurrentTasks) {
                // 添加到队列
                store.addToQueue(task)
                return
            }

            try {
                set(state => ({
                    currentTask: task,
                    isProcessing: true,
                    runningTasks: new Set([...state.runningTasks, taskId])
                }))

                // 创建执行上下文
                const executionContext: TaskExecutionContext = {
                    taskId,
                    startTime: new Date(),
                    progress: 0,
                    currentStep: '初始化任务',
                    totalSteps: 1,
                    logs: []
                }

                set(state => ({
                    executionContexts: { ...state.executionContexts, [taskId]: executionContext }
                }))

                // 开始状态轮询
                store.startStatusPolling(taskId)

                // 启动任务
                const apiClient = await getApiClient()
                const result = await apiClient.startTask(taskId, params || task.config.parameters)

                // 添加结果
                store.addTaskResult(taskId, result)

                // 更新任务状态
                const updatedTask = { ...task, status: 'completed' as TaskStatus }
                set(state => ({
                    tasks: { ...state.tasks, [taskId]: updatedTask }
                }))

            } catch (error) {
                store.handleTaskError(taskId, error)

                // 如果启用自动重试
                if (store.config.autoRetry) {
                    const errorInfo = store.errors[taskId]
                    if (errorInfo && errorInfo.retryCount < store.config.maxRetryAttempts) {
                        setTimeout(() => {
                            store.retryTask(taskId)
                        }, store.config.retryDelay)
                    }
                }
            } finally {
                set(state => {
                    const newRunningTasks = new Set(state.runningTasks)
                    newRunningTasks.delete(taskId)

                    return {
                        runningTasks: newRunningTasks,
                        isProcessing: newRunningTasks.size > 0
                    }
                })

                pollingManager.stop(taskId)
                store.updateStatistics()

                // 处理队列中的下一个任务
                store.processQueue()
            }
        },

        cancelTask: async (taskId: string) => {
            try {
                const apiClient = await getApiClient()
                await apiClient.cancelTask(taskId)

                set(state => {
                    const updatedTask = { ...state.tasks[taskId], status: 'cancelled' as TaskStatus }
                    const newRunningTasks = new Set(state.runningTasks)
                    newRunningTasks.delete(taskId)

                    return {
                        tasks: { ...state.tasks, [taskId]: updatedTask },
                        runningTasks: newRunningTasks,
                        isProcessing: newRunningTasks.size > 0
                    }
                })

                pollingManager.stop(taskId)
                get().updateStatistics()
            } catch (error) {
                get().handleTaskError(taskId, error)
            }
        },

        retryTask: async (taskId: string) => {
            const store = get()
            const errorInfo = store.errors[taskId]
            const retryCount = errorInfo ? errorInfo.retryCount + 1 : 1

            // 清除之前的错误
            store.clearTaskError(taskId)

            try {
                await store.startTask(taskId)
            } catch (error) {
                store.handleTaskError(taskId, error)

                // 更新重试次数
                set(state => ({
                    errors: {
                        ...state.errors,
                        [taskId]: createTaskError(taskId, error, retryCount)
                    }
                }))
            }
        },

        pauseTask: async (taskId: string) => {
            // 暂停任务的实现（需要后端支持）
            console.log(`Pausing task ${taskId} - not implemented yet`)
        },

        resumeTask: async (taskId: string) => {
            // 恢复任务的实现（需要后端支持）
            console.log(`Resuming task ${taskId} - not implemented yet`)
        },

        // Actions - 队列管理
        addToQueue: (task: Task, priority = 0) => {
            const queueItem: TaskQueueItem = {
                task,
                priority,
                queuedAt: new Date()
            }

            set(state => ({
                taskQueue: [...state.taskQueue, queueItem].sort((a, b) => b.priority - a.priority)
            }))
        },

        removeFromQueue: (taskId: string) => {
            set(state => ({
                taskQueue: state.taskQueue.filter(item => item.task.id !== taskId)
            }))
        },

        reorderQueue: (taskIds: string[]) => {
            const store = get()
            const reorderedQueue = taskIds.map(taskId =>
                store.taskQueue.find(item => item.task.id === taskId)
            ).filter(Boolean) as TaskQueueItem[]

            set({ taskQueue: reorderedQueue })
        },

        processQueue: async () => {
            const store = get()

            if (store.taskQueue.length === 0 || store.runningTasks.size >= store.maxConcurrentTasks) {
                return
            }

            const nextTask = store.taskQueue[0]
            if (nextTask) {
                store.removeFromQueue(nextTask.task.id)
                await store.startTask(nextTask.task.id)
            }
        },

        clearQueue: () => {
            set({ taskQueue: [] })
        },

        // Actions - 状态管理
        updateTaskStatus: (taskId: string, status: TaskStatusInfo) => {
            set(state => ({
                taskStatuses: { ...state.taskStatuses, [taskId]: status }
            }))

            // 更新执行上下文
            if (status.progress !== undefined) {
                set(state => {
                    const context = state.executionContexts[taskId]
                    if (context) {
                        return {
                            executionContexts: {
                                ...state.executionContexts,
                                [taskId]: {
                                    ...context,
                                    progress: status.progress || 0,
                                    currentStep: status.currentStep || context.currentStep,
                                    totalSteps: status.totalSteps || context.totalSteps
                                }
                            }
                        }
                    }
                    return state
                })
            }
        },

        pollTaskStatus: async (taskId: string) => {
            try {
                const apiClient = await getApiClient()
                const status = await apiClient.getTaskStatus(taskId)
                get().updateTaskStatus(taskId, status)

                // 如果任务完成，停止轮询并加载结果
                if (status.status === 'completed' || status.status === 'error' || status.status === 'cancelled') {
                    pollingManager.stop(taskId)

                    if (status.status === 'completed') {
                        await get().loadTaskResults(taskId)
                    }
                }
            } catch (error) {
                console.error(`Failed to poll status for task ${taskId}:`, error)
            }
        },

        startStatusPolling: (taskId: string) => {
            const store = get()
            pollingManager.start(
                taskId,
                () => store.pollTaskStatus(taskId),
                store.config.pollingInterval
            )
        },

        stopStatusPolling: (taskId: string) => {
            pollingManager.stop(taskId)
        },

        // Actions - 结果管理
        loadTaskResults: async (taskId: string) => {
            try {
                const apiClient = await getApiClient()
                const results = await apiClient.getTaskResults(taskId)
                set(state => ({
                    results: { ...state.results, [taskId]: results }
                }))
            } catch (error) {
                console.error(`Failed to load results for task ${taskId}:`, error)
            }
        },

        addTaskResult: (taskId: string, result: TaskResult) => {
            set(state => ({
                results: {
                    ...state.results,
                    [taskId]: [...(state.results[taskId] || []), result]
                }
            }))
        },

        clearTaskResults: (taskId: string) => {
            set(state => {
                const { [taskId]: deleted, ...remainingResults } = state.results
                return { results: remainingResults }
            })
        },

        // Actions - 错误处理
        handleTaskError: (taskId: string, error: unknown) => {
            const store = get()
            const existingError = store.errors[taskId]
            const retryCount = existingError ? existingError.retryCount : 0

            const errorInfo = createTaskError(taskId, error, retryCount)

            set(state => ({
                errors: { ...state.errors, [taskId]: errorInfo }
            }))

            // 添加错误日志
            if (store.config.enableLogging) {
                store.addTaskLog(taskId, {
                    level: 'error',
                    message: errorInfo.message,
                    details: errorInfo.details
                })
            }
        },

        clearTaskError: (taskId: string) => {
            set(state => {
                const { [taskId]: deleted, ...remainingErrors } = state.errors
                return { errors: remainingErrors }
            })
        },

        clearAllErrors: () => {
            set({ errors: {} })
        },

        // Actions - 日志管理
        addTaskLog: (taskId: string, log: Omit<TaskLog, 'id' | 'timestamp'>) => {
            const newLog: TaskLog = {
                ...log,
                id: generateId(),
                timestamp: new Date()
            }

            set(state => {
                const context = state.executionContexts[taskId]
                if (context) {
                    return {
                        executionContexts: {
                            ...state.executionContexts,
                            [taskId]: {
                                ...context,
                                logs: [...context.logs, newLog]
                            }
                        }
                    }
                }
                return state
            })
        },

        getTaskLogs: (taskId: string) => {
            const store = get()
            const context = store.executionContexts[taskId]
            return context ? context.logs : []
        },

        clearTaskLogs: (taskId: string) => {
            set(state => {
                const context = state.executionContexts[taskId]
                if (context) {
                    return {
                        executionContexts: {
                            ...state.executionContexts,
                            [taskId]: {
                                ...context,
                                logs: []
                            }
                        }
                    }
                }
                return state
            })
        },

        // Actions - 统计和配置
        updateStatistics: () => {
            const store = get()
            const tasks = Object.values(store.tasks)

            const statistics: TaskStatistics = {
                total: tasks.length,
                completed: tasks.filter(t => t.status === 'completed').length,
                failed: tasks.filter(t => t.status === 'error').length,
                running: tasks.filter(t => t.status === 'running').length,
                pending: tasks.filter(t => t.status === 'pending').length,
                cancelled: tasks.filter(t => t.status === 'cancelled').length,
                averageExecutionTime: 0, // 需要根据执行上下文计算
                successRate: 0
            }

            if (statistics.total > 0) {
                statistics.successRate = (statistics.completed / statistics.total) * 100
            }

            set({ statistics })
        },

        updateConfig: (newConfig: Partial<TaskStore['config']>) => {
            set(state => ({
                config: { ...state.config, ...newConfig }
            }))
        },

        resetStore: () => {
            pollingManager.stopAll()

            set({
                tasks: {},
                currentTask: null,
                taskQueue: [],
                executionContexts: {},
                results: {},
                taskStatuses: {},
                errors: {},
                isProcessing: false,
                runningTasks: new Set(),
                statistics: { ...defaultStatistics }
            })
        }
    }))
)